package com.hongxun.budget.ui.activity.tk;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hongxun.budget.R;
import com.hongxun.budget.greendao.DMaterialModelEntityDao;
import com.hongxun.budget.greendao.DMaterialModelItemEntityDao;
import com.hongxun.budget.greendao.DaoSession;
import com.hongxun.budget.ui.activity.BaseActivity;
import com.hongxun.budget.ui.dialog.NoticeDialog;
import com.hongxun.budget.utils.DBUtils;
import com.hongxun.budget.utils.GreenDaoManager;
import com.hongxun.budget.utils.RecyclerViewUtils;
import com.hongxun.budget.utils.T;
import com.hongxun.greenentity.tk.BDataDictionaryEntity;
import com.hongxun.greenentity.tk.BMaterialEntity;
import com.hongxun.greenentity.tk.DMaterialModelEntity;
import com.hongxun.greenentity.tk.DMaterialModelItemEntity;
import com.hongxun.interfaces.ClickListener;
import com.hongxun.net.ProjectNet;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MaterialModelActivity extends BaseActivity {


    @BindView(R.id.right_save)
    Button rightSave;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.list2)
    RecyclerView list2;
    boolean c;
    SuperAdapter<BDataDictionaryEntity> adapter1;
    SuperAdapter<DMaterialModelEntity> adapter2;
    List<DMaterialModelEntity> datas = new ArrayList<>();
    @BindView(R.id.right_btn)
    Button rightBtn;

    @Override
    public int getLayoutId() {
        return R.layout.activity_material_model;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        final Intent intent = getIntent();
        c = intent.getBooleanExtra("choice", false);
        if (c) {
            rightSave.setVisibility(View.GONE);
            rightBtn.setVisibility(View.GONE);
        } else {
            rightBtn.setVisibility(View.VISIBLE);
            rightBtn.setText("更新");
            rightSave.setVisibility(View.VISIBLE);
            rightSave.setText("新增");
        }
        List<BDataDictionaryEntity> dataDictionaryEntities = DBUtils.getBDataDictionaryEntities("material_model");
        type = dataDictionaryEntities.get(0).getDValue();
        list.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(context));
        list.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        list.setAdapter(adapter1 = new SuperAdapter<BDataDictionaryEntity>(R.layout.content_adddevice_left) {
            @Override
            public void bindView(ViewHolder viewHolder, final BDataDictionaryEntity b, int i) {
                TextView t = viewHolder.getView(R.id.label);
                t.setText(b.getDValue());
                if (b.getDValue().equals(type)) {
                    t.setBackgroundResource(R.drawable.view_bottom_textpre);
                } else {
                    t.setBackgroundResource(R.color.white);
                }
                viewHolder.getView(R.id.label).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        type = b.getDValue();
                        adapter1.notifyDataSetChanged();
                        getData();
                    }
                });
            }
        });
        adapter1.setData(dataDictionaryEntities);
        list2.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForVertical(context));
        list2.setAdapter(adapter2 = new SuperAdapter<DMaterialModelEntity>(R.layout.content_material_model) {
            @Override
            public void bindView(ViewHolder viewHolder, final DMaterialModelEntity dMaterialModelEntity, int i) {
                ((TextView) viewHolder.getView(R.id.name)).setText(dMaterialModelEntity.getName());
                ((TextView) viewHolder.getView(R.id.parameter)).setText(dMaterialModelEntity.getContent());
                viewHolder.getView(R.id.layout).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (c) {//选择
                            List<DMaterialModelItemEntity> list = GreenDaoManager.getInstance().getmDaoSession().getDMaterialModelItemEntityDao().queryBuilder().where(
                                    DMaterialModelItemEntityDao.Properties.ModelGuid.eq(dMaterialModelEntity.getGuid())
                                    , DMaterialModelItemEntityDao.Properties.Datastate.notEq("删除")
                            ).list();
                            List<BMaterialEntity> bMaterialEntities = new ArrayList<BMaterialEntity>();
                            for (DMaterialModelItemEntity d : list) {
                                BMaterialEntity load = GreenDaoManager.getInstance().getmDaoSession().getBMaterialEntityDao().load(d.getMaterialGuid());
                                load.setmCount(d.getCount());
                                bMaterialEntities.add(load);
                            }
                            Intent intent1 = new Intent();
                            intent1.putExtra("material", (Serializable) bMaterialEntities);
                            setResult(Activity.RESULT_OK, intent1);
                            finish();
                        } else {//修改
                            Intent intent1 = new Intent(context, AddMaterialModelActivity.class);
                            intent1.putExtra("guid", dMaterialModelEntity.getGuid());
                            startActivity(intent1);
                        }
                    }
                });
                viewHolder.getView(R.id.layout).setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {//删除本地
                        new NoticeDialog().setMsg("是否删除本地?").setCancelButton("取消", null).setConfirmButton("删除", new ClickListener() {
                            @Override
                            public void click() {
                                datas.remove(dMaterialModelEntity);
                                adapter2.notifyDataSetChanged();
                                GreenDaoManager.getInstance().getmDaoSession().getDMaterialModelEntityDao().delete(dMaterialModelEntity);
                            }
                        }).show(getFragmentManager(), "");
                        return false;
                    }
                });
            }
        });
        adapter2.setData(datas);
        adapter2.setEmptyDataView(R.layout.view_empty);
    }

    String type;

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    private void getData() {
        datas.clear();
        List<DMaterialModelEntity> entityList = GreenDaoManager.getInstance().getmDaoSession().getDMaterialModelEntityDao().queryBuilder()
                .where(DMaterialModelEntityDao.Properties.Type.eq(type), DMaterialModelEntityDao.Properties.Datastate.notEq("删除")).list();
        datas.addAll(entityList);
        adapter2.notifyDataSetChanged();
    }


    @OnClick({R.id.right_btn, R.id.right_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.right_btn://服务器更新
                new NoticeDialog().setMsg("是否更新材料模块？")
                        .setCancelButton("取消", null).setConfirmButton("更新", new ClickListener() {
                    @Override
                    public void click() {
                        ProjectNet.updateMaterialModel(context, MaterialModelActivity.this);
                    }
                }).show(getFragmentManager(), "");
                break;
            case R.id.right_save://新增
                startActivity(new Intent(context, AddMaterialModelActivity.class));
                break;
        }
    }

    @Override
    public void success(int i, JSONObject obj) {
        List<DMaterialModelEntity> dMaterialModelEntities = JSON.parseArray(obj.getString("dMaterialModelEntities"), DMaterialModelEntity.class);
        List<DMaterialModelItemEntity> dMaterialModelItemEntities = JSON.parseArray(obj.getString("dMaterialModelItemEntities"), DMaterialModelItemEntity.class);
        for (DMaterialModelEntity d : dMaterialModelEntities) {
            d.setDatastate("已同步");
        }
        for (DMaterialModelItemEntity d : dMaterialModelItemEntities) {
            d.setDatastate("已同步");
        }
        DaoSession session = GreenDaoManager.getInstance().getmDaoSession();
        session.getDMaterialModelEntityDao().deleteAll();
        session.getDMaterialModelItemEntityDao().deleteAll();
        session.getDMaterialModelEntityDao().insertOrReplaceInTx(dMaterialModelEntities);
        session.getDMaterialModelItemEntityDao().insertOrReplaceInTx(dMaterialModelItemEntities);
        getData();
        T.showLong(context, "更新完成");
    }
}
